package com.example.demo.heima.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname NettyServerHandler2
 * @description
 * @date 2023/07/21 22:35
 * <p>
 * ******************************************************
 */
public class NettyServerInBoundHandler2 extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyServerHandler2 channelActive");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyServerHandler2 channelInactive");
        super.channelInactive(ctx);
    }

    /**
     * 有数据时回调
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 可能上一个handler已经将数据读完，就可能独到的数据为空
        System.out.println("NettyServerHandler2 channelRead");

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);

        String content = new String(bytes, Charset.defaultCharset());
        System.out.println("收到的数据：" + content);
        super.channelRead(ctx, msg);
    }

    /**
     * bytebuf读完数据的回调
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyServerHandler2 channelReadComplete");

        /*// 向客户端写回数据
        Channel channel = ctx.channel();
        ByteBuf buffer = channel.alloc().buffer();
        buffer.writeBytes("hello nioclient".getBytes(StandardCharsets.UTF_8));
        channel.writeAndFlush(buffer);*/
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("NettyServerHandler2 exceptionCaught" + cause.getMessage());
        super.exceptionCaught(ctx, cause);
    }
}
